import {
  DBPost
} from "../../../data/db-cloud.js";

Page({
  data: {
    post:{},
    collectionNum: 0,
    commentNum:0,
  },
  async onLoad(options) {
    const postId = options.id;
    this.dbPost = new DBPost(postId);
    const postData = await this.dbPost.getPostItemById();
    const collection = await this.dbPost.getCollectionNum();
    const comments = await this.dbPost.getCommentData()
    console.log(comments)
    this.setData({
      post: postData,
      collectionNum:collection.length,
      commentNum: comments.length
    });
    wx.setNavigationBarTitle({
      title: postData.title,
    });
    this.addReadingTimes();
  },

  onCollectionTap(event) {
    const currentPost = this.data.post;
    this.dbPost.collect();
    wx.showToast({
      title: currentPost.collectionStatus ? "取消成功" : "收藏成功",
      duration: 1000,
      icon: "success",
      mask: true,
    });
    this._changeStatus(currentPost);
  },

  _changeStatus(currentPost) {
    const newStatus = !currentPost.collectionStatus;
    let newCollectionNum = 0;
    if (currentPost.collectionStatus) {
      newCollectionNum = currentPost.collectionNum - 1;
      console.log(newCollectionNum);
    } else {
      newCollectionNum = currentPost.collectionNum + 1;
      console.log(newCollectionNum);
    }
    this.setData({
      "post.collectionStatus": newStatus,
      "post.collectionNum": newCollectionNum,
    });
  },


  onCommentTap(event) {
    var id = event.currentTarget.dataset.postId;
    wx.navigateTo({
      url: '../post-comment/post-comment?id=' + id
    })
  },
  addReadingTimes() {
    this.dbPost.addReadingTimes()
  }
})